
package com.jf.cloud.service.sysmanager.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.constant.PubgConstant;
import com.jf.cloud.service.sysmanager.constant.TradeType;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.dao.*;
import com.jf.cloud.service.sysmanager.entity.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jf.cloud.service.sysmanager.common.base.BaseService;
import com.jf.cloud.service.sysmanager.common.base.GenericsUtils;
import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.BaseDao;
import com.jf.cloud.service.sysmanager.common.db.Condition;
import com.jf.cloud.service.sysmanager.common.taglib.Paging;


/**
 * 员工服务实现
 * 
 * @author 绝峰代码机1.0 创建时间：2018-03-31
 */
@Service("pubgExchangeOrderService")
public class PubgExchangeOrderServiceImpl extends BaseService<PubgExchangeOrder, Long> implements IPubgExchangeOrderService {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(PubgExchangeOrderServiceImpl.class);

	/**
	 * JPA公共DAO
	 */
	@Resource
	private BaseDao baseDao;

	private RowMapper<PubgExchangeOrder> rowMapper = new BeanPropertyRowMapper<PubgExchangeOrder>(GenericsUtils.getSuperClassGenricType(this.getClass()));

	/**
	 * 员工服务
	 */
	@Resource
	private IPubgUserService pubgUserService;

	/**
	 * 俱乐部服务
	 */
	@Resource
	private IPubgClubService pubgClubService;

	@Resource
	private IPubgTeamService pubgTeamService;

	@Resource
	private IPubgFinanceFlowDetailService pubgFinanceFlowDetailService;

	@Resource
	private IPubgOperateLogService pubgOperateLogService;

	/**
	 * 根据主键查询员工
	 * 
	 * @author 绝峰代码机1.0 创建时间：2018-03-31
	 */
	public PubgExchangeOrder findPubgExchangeOrder(Long rowId) throws Exception {
		try {
			return this.baseDao.findObject("", rowMapper, rowId);
		} catch (Exception e) {
			throw new Exception("根据主键查询员工出错！", e);
		}
	}

	/**
	 * 根据查询条件获取员工列表
	 * 
	 * @author 绝峰代码机1.0 创建时间：2018-03-31
	 */
	public List<PubgExchangeOrder> findPubgExchangeOrderList(Condition qc) throws Exception {
		try {
			return this.baseDao.findList("", rowMapper);
		} catch (Exception e) {
			throw new Exception("根据查询条件获取员工列表出错！", e);
		}
	}

	/**
	 * 新增/修改员工
	 * 
	 * @author 绝峰代码机1.0 创建时间：2018-03-31
	 */
	@Transactional
	public PubgExchangeOrder saveOrUpdatePubgExchangeOrder(PubgExchangeOrder pubgExchangeOrder) throws Exception {
		try {
			return this.baseDao.saveAll(pubgExchangeOrder);
		} catch (Exception e) {
			throw new Exception("新增/修改员工出错！", e);
		}
	}

	/**
	 * app获取兑换记录列表
	 * 
	 * @author 朱建文 创建时间：2018年4月11日 下午1:58:07
	 */
	public List<Map<String, Object>> getExchageOrderList(OPaging<Map<String, Object>> page) throws Exception {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		String sql = "SELECT ROW_ID rowId, GOODS_NAME goodsName, GOODS_PRICE goodsPrice, ";
		sql += " APPLY_TIME applyTime, CONVERSION_STATE state ";
		sql += " FROM pubg_exchange_order";
		sql += page.getWhereSQL(true);
        Paging<Map<String, Object>> pageTemp = this.baseDao.findObjectListMapByPage(sql, page, page.getParamList().toArray());
		dataList = pageTemp.getDataList();
		return dataList;
	}

	/**
	 * 兑换商品
	 * @author 高冬冬 2018年4月12日
	 */
	@Transactional
	public void addExchangeOrder(PubgExchangeOrder pubgExchangeOrder) throws Exception {
		try {
			baseDao.saveAll(pubgExchangeOrder);
			if (pubgExchangeOrder.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {
				String updateSqlReturn = "UPDATE pubg_user SET BALANCE = IFNULL(BALANCE,0) - ? WHERE ROW_ID = ? AND IFNULL(BALANCE,0) > ? ";
				baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getUserId(), pubgExchangeOrder.getGoodsPrice());
				updateSqlReturn = "UPDATE pubg_user_team SET USER_TEAM_BALANCE = IFNULL(USER_TEAM_BALANCE,0) - ? WHERE USER_ID = ? AND TEAM_ID = ? AND CLUB_ID = ? AND IFNULL(USER_TEAM_BALANCE,0) > ? ";
				baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getUserId(), pubgExchangeOrder.getTeamId(), pubgExchangeOrder.getClubId(), pubgExchangeOrder.getGoodsPrice());
				updateSqlReturn = "UPDATE pubg_user_club SET USER_CLUB_BALANCE = IFNULL(USER_CLUB_BALANCE,0) - ? WHERE USER_ID = ? AND CLUB_ID = ? AND IFNULL(USER_CLUB_BALANCE,0) > ? ";
				baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getUserId(), pubgExchangeOrder.getClubId(), pubgExchangeOrder.getGoodsPrice());
			} else if (pubgExchangeOrder.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue()) {
				String updateSql = "UPDATE pubg_team SET TEAM_BALANCE = IFNULL(TEAM_BALANCE,0) - ? WHERE ROW_ID = ? AND IFNULL(TEAM_BALANCE,0) > ? ";
				baseDao.update(updateSql.toString(), pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getTeamId(), pubgExchangeOrder.getGoodsPrice());
			} else if (pubgExchangeOrder.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()) {
				String updateSql = "UPDATE pubg_club SET CLUB_BALANCE = IFNULL(CLUB_BALANCE,0) - ? WHERE ROW_ID = ? AND IFNULL(CLUB_BALANCE,0) > ? ";
				baseDao.update(updateSql.toString(), pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getClubId(), pubgExchangeOrder.getGoodsPrice());
			}
		} catch (Exception e) {
			throw new RuntimeException("兑换商品出错！", e);
		}
	}

	/**
	 * 修改商场物品兑换订单状态
	 * @author 高冬冬 2018年4月12日
	 * orderId:订单ID conversionState:更新状态 optId:操作人ID optAccount:操作人账号
	 * fromType:请求来源（manage:后台管理系统），app请求不传此参数
	 */
	@Transactional
	public void updateOrderConversionState(Long orderId, String conversionState, Long optId, String optAccount, String fromType) throws Exception {
		try {
			List<Object> params = new ArrayList<Object>();
			params.add(conversionState);
			params.add(DateUtil.getCurrentDateTime());
			params.add(orderId);

			String updateSql = "UPDATE pubg_exchange_order SET CONVERSION_STATE=?, MANAGE_TIME=? WHERE ROW_ID=? AND CONVERSION_STATE='10'";
			baseDao.update(updateSql, params.toArray());
			PubgExchangeOrder pubgExchangeOrder = findByPK(orderId);
			PubgUser orderUser = pubgUserService.findByPK(pubgExchangeOrder.getUserId());//兑换商品用户
			//构建资金流水对象 BEGIN
			PubgFinanceFlowDetail pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
			if (PubgConstant.CONVERSION_STATE_20.equals(conversionState)) {
				pubgFinanceFlowDetail.setTradeTypeId(TradeType.EX_ORDER_SUCCESS.key());
				pubgFinanceFlowDetail.setTradeTypeName(TradeType.EX_ORDER_SUCCESS.value());
				pubgFinanceFlowDetail.setInOutFlag(PubgConstant.FINANCE_FLOW_OUT);
				pubgFinanceFlowDetail.setClubId(pubgExchangeOrder.getClubId());
				pubgFinanceFlowDetail.setClubName(pubgExchangeOrder.getClubName());
				pubgFinanceFlowDetail.setTeamId(pubgExchangeOrder.getTeamId());
				pubgFinanceFlowDetail.setTeamName(pubgExchangeOrder.getTeamName());
				pubgFinanceFlowDetail.setUserId(pubgExchangeOrder.getUserId());
				pubgFinanceFlowDetail.setUserAccount(pubgExchangeOrder.getUserAccount());
				pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
				pubgFinanceFlowDetail.setTradeMoney(pubgExchangeOrder.getGoodsPrice());//客户端传递的变化鸡蛋数量
				if ("manage".equals(fromType)) {//后台处理部长的兑换
					if (orderUser.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()) {
						PubgClub pubgClub = pubgClubService.findByPK(pubgExchangeOrder.getClubId());//俱乐部
						pubgFinanceFlowDetail.setTradeMoneyAfter(pubgClub.getClubBalance());//更新后的鸡蛋数量
						pubgFinanceFlowDetailService.saveOrUpdatePubgFinanceFlowDetail(pubgFinanceFlowDetail);
					}
				} else {//前台兑换的处理
					PubgUser loginUser = pubgUserService.findByPK(optId);//当前登陆用户
					if (loginUser.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()) {
						if (orderUser.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue()) {
							PubgTeam pubgTeam = pubgTeamService.findByPK(pubgExchangeOrder.getTeamId());//战队
							pubgFinanceFlowDetail.setTradeMoneyAfter(pubgTeam.getTeamBalance());//更新后的鸡蛋数量
						}
						if (orderUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {
							pubgFinanceFlowDetail.setTradeMoneyAfter(orderUser.getBalance());//更新后的鸡蛋数量
						}
					} else if (loginUser.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue() && orderUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {
						pubgFinanceFlowDetail.setTradeMoneyAfter(orderUser.getBalance());//更新后的鸡蛋数量
					}
					pubgFinanceFlowDetailService.saveOrUpdatePubgFinanceFlowDetail(pubgFinanceFlowDetail);
				}
			} else if (PubgConstant.CONVERSION_STATE_30.equals(conversionState)) {
				if ("manage".equals(fromType)) {//后台处理部长的撤销
					if (pubgExchangeOrder.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()) {
						PubgClub pubgClub = pubgClubService.findByPK(pubgExchangeOrder.getClubId());//俱乐部
						String updateSqlReturn = "UPDATE pubg_club SET CLUB_BALANCE = IFNULL(CLUB_BALANCE,0) + ? WHERE ROW_ID = ? ";
						baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), pubgClub.getRowId());
					}
				} else {//前台兑换的撤销
					PubgUser loginUser = pubgUserService.findByPK(optId);//当前登陆用户
					if (loginUser.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()) {
						if (orderUser.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue()) {
							PubgTeam pubgTeam = pubgTeamService.findByPK(pubgExchangeOrder.getTeamId());//战队
							String updateSqlReturn = "UPDATE pubg_team SET TEAM_BALANCE = IFNULL(TEAM_BALANCE,0) + ? WHERE ROW_ID = ? ";
							baseDao.update(updateSql.toString(), pubgExchangeOrder.getGoodsPrice(), pubgTeam.getRowId());
						}
						if (orderUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {
							String updateSqlReturn = "UPDATE pubg_user SET BALANCE = IFNULL(BALANCE,0) + ? WHERE ROW_ID = ? ";
							baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), orderUser.getRowId());
							updateSqlReturn = "UPDATE pubg_user_team SET USER_TEAM_BALANCE = IFNULL(USER_TEAM_BALANCE,0) + ? WHERE USER_ID = ? AND TEAM_ID = ? AND CLUB_ID = ? ";
							baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), orderUser.getRowId(), pubgExchangeOrder.getTeamId(), pubgExchangeOrder.getClubId());
							updateSqlReturn = "UPDATE pubg_user_club SET USER_CLUB_BALANCE = IFNULL(USER_CLUB_BALANCE,0) + ? WHERE USER_ID = ? AND CLUB_ID = ? ";
							baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), orderUser.getRowId(), pubgExchangeOrder.getClubId());
						}
					} else if (loginUser.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue() && orderUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {
						String updateSqlReturn = "UPDATE pubg_user SET BALANCE = IFNULL(BALANCE,0) + ? WHERE ROW_ID = ? ";
						baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), orderUser.getRowId());
						updateSqlReturn = "UPDATE pubg_user_team SET USER_TEAM_BALANCE = IFNULL(USER_TEAM_BALANCE,0) + ? WHERE USER_ID = ? AND TEAM_ID = ? AND CLUB_ID = ? ";
						baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), orderUser.getRowId(), pubgExchangeOrder.getTeamId(), pubgExchangeOrder.getClubId());
						updateSqlReturn = "UPDATE pubg_user_club SET USER_CLUB_BALANCE = IFNULL(USER_CLUB_BALANCE,0) + ? WHERE USER_ID = ? AND CLUB_ID = ? ";
						baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), orderUser.getRowId(), pubgExchangeOrder.getClubId());
					}
				}
			}
			//构建资金流水对象 END
			//构建操作日志对象 BEGIN
			PubgOperateLog pubgOperateLog = new PubgOperateLog();
			pubgOperateLog.setClubId(pubgExchangeOrder.getClubId());
			pubgOperateLog.setClubName(pubgExchangeOrder.getClubName());
			pubgOperateLog.setTeamId(pubgExchangeOrder.getTeamId());
			pubgOperateLog.setTeamName(pubgExchangeOrder.getTeamName());
			pubgOperateLog.setUserId(pubgExchangeOrder.getUserId());
			pubgOperateLog.setUserAccount(pubgExchangeOrder.getUserAccount());
			pubgOperateLog.setOptId(optId);
			pubgOperateLog.setOptName(optAccount);
			pubgOperateLog.setOptTime(DateUtil.getCurrentDateTime());
			String content = "";
			if (PubgConstant.CONVERSION_STATE_20.equals(pubgExchangeOrder.getConversionState())) {
				content = "兑换订单处理完成，操作人：" + optAccount;
				pubgOperateLog.setContent(content);
				pubgOperateLog.setOptType(TradeType.EX_ORDER_SUCCESS.key());
				pubgOperateLogService.saveOrUpdatePubgOperateLog(pubgOperateLog);
			} else if (PubgConstant.CONVERSION_STATE_30.equals(pubgExchangeOrder.getConversionState())) {
				content = "兑换订单撤销兑换，操作人：" + optAccount;
				pubgOperateLog.setContent(content);
				pubgOperateLog.setOptType(TradeType.EX_ORDER_CANCEL.key());
				pubgOperateLogService.saveOrUpdatePubgOperateLog(pubgOperateLog);
			}
			//构建操作日志对象 END
			baseDao.saveAll(pubgFinanceFlowDetail);

		} catch (Exception e) {
			throw new RuntimeException("修改商场物品兑换订单状态出错！", e);
		}
	}
}
